package com.platform.common.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.platform.common.bean.BaseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * describe:公共控制器
 *
 * @author rainly
 * @date 2019/11/08
 * @time 9:01 上午
 */
@Slf4j
public class BaseController<T extends BaseEntity> {
    /**
     * 默认分页每页显示数量
     */
    @Value("${pageSize}")
    public int pageSize;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 获得HttpServletRequest
     * @return HttpServletRequest
     */
    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获得RequestBody
     * @return RequestBody的字符串
     */
    public String getRequestBody(){
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(getRequest().getInputStream(), StandardCharsets.UTF_8));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            log.error("RequestBodyIO编码格式错误",e.fillInStackTrace());
        } catch (IOException e) {
            log.error("RequestBodyIO错误",e.fillInStackTrace());
        }
        return null;
    }

    /**
     * 全局请求处理，可用于公共功能处理，如token,IP记录等
     * @param model model
     * @param request request
     */
    //TODO 了解一下执行顺序
    @ModelAttribute
    public void doAttributes(Model model, HttpServletRequest request) {
        log.info("全局请求处理");
    }
}
